package com.at.transform4;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/9/25 15:07
 */
public class RichFunctionDemo4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        DataStreamSource<Integer> source = env.fromElements(1, 2, 3, 4);

        /**
         * RichXXXFunction: 富函数
         * 1、多了生命周期管理方法：
         *   open(): 每个子任务，在启动时，调用一次
         *   close(): 每个子任务，在结束时，调用一次
         *
         * 2、多了一个运行时上下文
         *   可以获取一些运行时的环境信息，比如 子任务编号、名称、其他的。。。。
         */
        SingleOutputStreamOperator<Integer> map = source.map(new RichMapFunction<Integer, Integer>() {
            private static final long serialVersionUID = -7260840777534279749L;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);

                RuntimeContext runtimeContext = super.getRuntimeContext();
                System.out.println("子任务编号=" + runtimeContext.getIndexOfThisSubtask() + "启动，子任务名称="
                        + runtimeContext.getTaskNameWithSubtasks() + ",调用open()");
            }

            @Override
            public void close() throws Exception {
                super.close();
                RuntimeContext runtimeContext = super.getRuntimeContext();
                System.out.println("子任务编号=" + runtimeContext.getIndexOfThisSubtask() + "启动，子任务名称="
                        + runtimeContext.getTaskNameWithSubtasks() + ",调用close()");
            }

            @Override
            public Integer map(Integer value) throws Exception {
                return value + 1;
            }
        });

        map.print();

        env.execute();
    }
}
